import { FastifyPluginAsync } from 'fastify'
import { ObjectId } from 'mongodb'

interface Message {
  text: string
  author: string
  createdAt?: Date
}

const messagesRoutes: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  // 获取MongoDB集合
  const db = fastify.mongo.db
  // 获取集合的辅助函数
  const getCollection = () => {
    // @ts-ignore
    return db.collection('rooms')
  }

  // 获取所有消息
  fastify.get('/a', async function (request, reply) {
    const collection = getCollection()
    const messages = await collection.find().sort({ createdAt: -1 }).toArray()
    return { success: true, data: messages }
  })

  // 创建新消息
  fastify.post('/', async function (request, reply) {
    const { text, author } = request.body as Message

    if (!text || !author) {
      reply.code(400)
      return { success: false, error: '缺少必要字段' }
    }

    const collection = getCollection()
    const result = await collection.insertOne({
      text,
      author,
      createdAt: new Date()
    })

    return {
      success: true,
      data: {
        id: result.insertedId,
        text,
        author
      }
    }
  })

  // 根据ID获取消息
  fastify.get('/:id', async function (request, reply) {
    const { id } = request.params as { id: string }

    try {
      const collection = getCollection()
      const message = await collection.findOne({ _id: new ObjectId(id) })

      if (!message) {
        reply.code(404)
        return { success: false, error: '消息不存在' }
      }

      return { success: true, data: message }
    } catch (err) {
      reply.code(400)
      return { success: false, error: '无效的ID格式' }
    }
  })

  // 更新消息
  fastify.put('/:id', async function (request, reply) {
    const { id } = request.params as { id: string }
    const { text, author } = request.body as Message

    if (!text && !author) {
      reply.code(400)
      return { success: false, error: '至少需要提供一个更新字段' }
    }

    try {
      const collection = getCollection()
      const updateData: Partial<Message> = {}

      if (text) updateData.text = text
      if (author) updateData.author = author

      const result = await collection.updateOne(
        { _id: new ObjectId(id) },
        { $set: updateData }
      )

      if (result.matchedCount === 0) {
        reply.code(404)
        return { success: false, error: '消息不存在' }
      }

      return { success: true, data: { id, ...updateData } }
    } catch (err) {
      reply.code(400)
      return { success: false, error: '更新失败' }
    }
  })

  // 删除消息
  fastify.delete('/:id', async function (request, reply) {
    const { id } = request.params as { id: string }

    try {
      const collection = getCollection()
      const result = await collection.deleteOne({ _id: new ObjectId(id) })

      if (result.deletedCount === 0) {
        reply.code(404)
        return { success: false, error: '消息不存在' }
      }

      return { success: true, message: '消息已删除' }
    } catch (err) {
      reply.code(400)
      return { success: false, error: '删除失败' }
    }
  })
}

export default messagesRoutes
